(function ($) {
    if ($.fn.simpleSwitch) return;

    // toggle-on, toggle-off
    function on_view_clicked () {
        var view = $(this), shadow = view.data ('shadow')/*, checked*/;
        if (!shadow) {
            return;
        }

        shadow.prop ('checked', !shadow.is (':checked'));
        change_state (view, shadow);
    }

    function checkbox_handler () {
        var shadow = $(this), view = shadow.data ('view')/*, checked*/;
        if (!view) {
            return;
        }

        change_state (view, shadow);
    }

    function change_state (view, shadow) {
        if (shadow.is (':checked')) {
            view.addClass ('checked');
        } else {
            view.removeClass ('checked');
        }
    }

    $.fn.simpleSwitch = function () {
        var opts, command;
        if (typeof arguments[0] === 'string') {
            command = arguments [0];
        } else {
            opts = arguments [0];
        }

        return this.each (function () {
            var self = $(this).hide (), label, created = self.data ('created'), view;
            if (!created) {
                label = $('<label/>').insertAfter (self);
                view  = $('<div class="switch-root"><span class="switch-bg"></span>' +
                          '<span class="switch-handler"></span></div>').data('shadow', self).appendTo (label);
                self.data('view', view).addClass('simple-switch').appendTo(label);
                if (self.is(':checked')) {
                    view.addClass('checked');
                }
                self.on('change', checkbox_handler);
                self.data ('created', true);
                if (typeof opts === 'object') {
                    self.data ('settings', opts);
                }
            } else {
                view = self.data ('view');
            }

            switch (command) {
                case 'on':
                    self.prop ('checked', true);
                    change_state (view, self);
                    break;
                case 'off':
                    self.prop ('checked', false);
                    change_state (view, self);
                    break;
                case 'toggle':
                    self.prop ('checked', !self.is (':checked'));
                    change_state (view, self);
                    break;
                case 'update':
                    change_state (view, self);
                    break;
                case 'destroy':
                    view.remove ();
                    self.show ().removeData ('created');
                    break
            }
        });
    };

    $(function () {
        $('.simple-switch').simpleSwitch ();
    })
})(jQuery);